package com.briup.jdbc.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.briup.jdbc.conn.ConnectionImpl;
import com.briup.jdbc.extannotation.ExtParam;

public class AnalyseUtil {
	/**
	 * 解析SQL语句中条件字段
	 * 
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static List<String> analyseRequireSql(String sql) throws Exception {
		if (sql == null) {
			throw new Exception("sql is null !");
		}

		List<String> requireStrings = new ArrayList<String>();
		int startIndex = sql.indexOf("#{");
		int endIndex = -1;
		while (startIndex != -1) {
			startIndex += 2;
			endIndex = sql.indexOf("}", startIndex);
			requireStrings.add(sql.substring(startIndex, endIndex));
			startIndex = sql.indexOf("#{", endIndex);
		}
		return requireStrings;
	}

	/**
	 * 判断类型是不是自定义类型
	 * 
	 * @param type
	 * @return
	 */
	public static boolean isCustomizeType(Class<?> type) {
		if (type.getName().startsWith(ConnectionImpl.pojo)) {
			return true;
		}
		return false;
	}

	/**
	 * 将sql语句中的?替换下来
	 * 
	 * @param sql
	 * @param requireAttrNames
	 * @return
	 */
	public static String SQLReplaceAll(String sql, List<String> requireAttrNames) {
		for (String attrName : requireAttrNames) {
			sql = sql.replace("#{" + attrName + "}", "?");
		}
		return sql;
	}

	/**
	 * 请求属性替换成?
	 * 
	 * @param requireAttrNames
	 * @param method
	 * @param sql
	 * @param args
	 * @return
	 * @throws SecurityException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws NoSuchFieldExceptio
	 * @throws Exception
	 */
	public static Map<String, Object> replaceRequireParams(List<String> requireAttrNames, Method method, String sql,
			Object[] args)
			throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		// 打印日志,原sql语句
		System.out.println("Log>> sql >>" + sql);
		Map<String, Object> tempRequiresMap = new HashMap<String, Object>();
		Parameter[] parameters = method.getParameters();
		// 将所有的参数放置到临时map中
		for (int i = 0; i < parameters.length; i++) {
			ExtParam extParam = parameters[i].getDeclaredAnnotation(ExtParam.class);
			String paramName = extParam.value();
			Object object = args[i];
			tempRequiresMap.put(paramName, object);
		}
		// 替换所有的#{...}
		Map<String, Object> requiresMap = new HashMap<String, Object>();
		for (String requireName : requireAttrNames) {
			Parameter temParameter = null;
			Object tempObj = null;
			if (requireName.contains(".")) {
				String[] split = requireName.split("\\.");
				Object object = tempRequiresMap.get(split[0]);
				Field field = object.getClass().getDeclaredField(split[1]);
				field.setAccessible(true);
				tempObj = field.get(object);
			} else {
				tempObj = tempRequiresMap.get(requireName);
			}
			requiresMap.put(requireName, tempObj);
		}
		// 打印日志
		System.out.println("Log>>params>>" + requiresMap);
		return requiresMap;
	}

	// insert特制
	public static List<Map<String, Object>> replaceInsertRequireParams(List<String> requireAttrNames, Method method,
			String sql, Object[] args) throws Exception {
		// 打印日志,原sql语句
		System.out.println("Log>> sql >>" + sql);

		List<Map<String, Object>> requiresMapsList = new ArrayList<Map<String, Object>>();
		Object paramObject = args[0];
		if (paramObject instanceof List) {
			List<Object> paramList = (List<Object>) paramObject;
			for (Object object : paramList) {
				Map<String, Object> requiresMap = replaceInsertRequireParams_Map(requireAttrNames, object);
				requiresMapsList.add(requiresMap);
			}

		} else if (paramObject.getClass().getName().startsWith(ConnectionImpl.pojo)) {
			Map<String, Object> requiresMap = replaceInsertRequireParams_Map(requireAttrNames, paramObject);
			requiresMapsList.add(requiresMap);
		} else {
			throw new Exception("insert-sql-param must List<+" + ConnectionImpl.pojo + "* " + "+> or "
					+ ConnectionImpl.pojo + "* !");
		}
		// 打印日志
		System.out.println("Log>>params>>" + requiresMapsList);
		return requiresMapsList;
	}

	private static Map<String, Object> replaceInsertRequireParams_Map(List<String> requireAttrNames, Object object)
			throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Map<String, Object> requiresMap = new LinkedHashMap<String, Object>();
		Class<? extends Object> objClass = object.getClass();
		for (String attrName : requireAttrNames) {
			Field field = objClass.getDeclaredField(attrName);
			field.setAccessible(true);
			Object objValue = field.get(object);
			requiresMap.put(attrName, objValue);
//			System.out.println(attrName + ">>>" + objValue); // ===========
		}
//		System.out.println(requireAttrNames); // ------------------
//		System.out.println(requiresMap); // --------------------
		return requiresMap;
	}
}
